﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;

class BillInfo
{
    public string name;
    public float price;
    public int Num;
    public float offPrice;
}

public class SuanQian : MonoBehaviour
{
	RectTransform btnCountPos;
    RectTransform btnAddPos;

    InputField total;
    Text otherInfo;

    Transform grid;
    GameObject baseInfo;
    List<GameObject> baseInfos = new List<GameObject>();

	Image img;

    void Awake()
    {
        Transform tra_btn_Count = transform.Find("Detail/ButtonCount");
        Button btn_Count = tra_btn_Count.GetComponent<Button>();
        btn_Count.onClick.AddListener(Count);
        btnCountPos = tra_btn_Count.GetComponent<RectTransform>();

        Transform tra_btn_Add = transform.Find("Detail/Button+");
        Button btn_Add = tra_btn_Add.GetComponent<Button>();
        btn_Add.onClick.AddListener(OnBtnAdd);
        btnAddPos = tra_btn_Add.GetComponent<RectTransform>();

        total = transform.Find("Total/InputField").GetComponent<InputField>();
        otherInfo = transform.Find("Total/OtherInfo").GetComponent<Text>();

        grid = transform.Find("Detail/Grid");
        baseInfo = grid.Find("Info").gameObject;
        baseInfos.Add(baseInfo);
        InitBillObj(baseInfo);

        //默认两个
        OnBtnAdd();

		//二维码图片
		var tranImg = transform.Find("Total/Image");
		img = tranImg.GetComponent<Image>();
		Button btn_Img = tranImg.GetComponent<Button>();
		btn_Img.onClick.AddListener(ChoseImg);
		StartCoroutine(GetTexture());
	}

	void Count()
    {
        float nPay = TryGetTotalCost();
        if (nPay <= 0)
        {
            otherInfo.text = "支付价格 信息错误 !!!";
            return;
        }

        float nOri = 0;
        List<BillInfo> infos = new List<BillInfo>();
        for (int i = 0; i < baseInfos.Count; ++i)
        {
            BillInfo info = GetBillInfo(baseInfos[i]);
            if (!CheckBilInfo(info))
            {
                otherInfo.text = string.Format("{0} 信息错误 !!!", info.name);
                return;
            }

            nOri += info.price * info.Num;
            infos.Add(info);
        }

        float nVal = 0;
        int nCount = 0;
        float rate = nPay / nOri;
        for (int i = 0; i < infos.Count; ++i)
        {
            BillInfo info = infos[i];
            info.offPrice = MyCeil(info.price * rate);
            nVal += info.offPrice * info.Num;
            nCount += info.Num;
            SetBillInfo(baseInfos[i], info);
        }

        otherInfo.text = string.Format("原价:{0:0.0}, 支付:{1:0.0}, 实际收:{2:0.0}, 总人数:{3}", nOri, nPay, nVal, nCount);
    }

    void OnBtnAdd()
    {
        GameObject newObj = GameObject.Instantiate(baseInfo);
        newObj.transform.parent = grid;
		RectTransform rect = newObj.GetComponent<RectTransform>();
		rect.localScale = Vector3.one;

        baseInfos.Add(newObj);
        InitBillObj(newObj);

        btnCountPos.position += new Vector3(0, -40, 0);
        btnAddPos.position += new Vector3(0, -40, 0);
    }

    void InitBillObj(GameObject billObj)
    {
        BillInfo info = new BillInfo();
        info.name = string.Format("类型{0}", baseInfos.Count);
        info.Num = 1;

        SetBillInfo(billObj, info);
    }

    void SetBillInfo(GameObject billObj, BillInfo info)
    {
        SetBillStrInfo(billObj, "In_Name", info.name.ToString());
        SetBillStrInfo(billObj, "In_Num", info.Num.ToString());

        if (info.price > 0)
            SetBillStrInfo(billObj, "In_Price", info.price.ToString());

        if (info.offPrice > 0)
            SetBillStrInfo(billObj, "In_Off", info.offPrice.ToString());
    }

    void SetBillStrInfo(GameObject billObj, string childName, string info)
    {
        Transform child = billObj.transform.Find(childName);
        child.GetComponent<InputField>().text = info;
    }

    BillInfo GetBillInfo(GameObject billObj)
    {
        BillInfo info = new BillInfo();
        info.name = GetBillStrInfo(billObj, "In_Name");
        info.price = GetBillFloatInfo(billObj, "In_Price");
        info.Num = GetBillIntInfo(billObj, "In_Num");
        info.offPrice = -1;

        return info;
    }

    bool CheckBilInfo(BillInfo info)
    {
        if (info.Num < 0 || info.price < 0)
        {
            return false;
        }

        return true;
    }

    string GetBillStrInfo(GameObject billObj, string childName)
    {
        Transform child = billObj.transform.Find(childName);
        return child.GetComponent<InputField>().text;
    }

    int GetBillIntInfo(GameObject billObj, string childName)
    {
        string szStr = GetBillStrInfo(billObj, childName);
        try
        {
            return int.Parse(szStr);
        }
        catch
        {
            return -1;
        }
    }

    float GetBillFloatInfo(GameObject billObj, string childName)
    {
        string szStr = GetBillStrInfo(billObj, childName);
        try
        {
            return float.Parse(szStr);
        }
        catch
        {
            return -1;
        }
    }

    private float TryGetTotalCost()
    {
        try
        {
            return float.Parse(total.text);
        }
        catch
        {
            return -1;
        }
    }

    float MyCeil(float num)
    {
        num = num * 10;
        num = Mathf.Ceil(num);
        return num * 0.1f;
    }

	void ChoseImg()
	{
		System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();

		ofd.Title = "请选择支付二维码";
		ofd.Multiselect = false;
		ofd.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp";

		if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
		{
			Debug.LogError(ofd.FileName);
			PlayerPrefs.SetString("ErweimaTu", ofd.FileName);
			StartCoroutine(GetTexture());
		}
	}

	IEnumerator GetTexture()
	{
		string url = PlayerPrefs.GetString("ErweimaTu");
		if (string.IsNullOrEmpty(url))
		{
			yield break;
		}

		Debug.LogError(url);
		WWW www = new WWW("file://" + url);
		yield return www;
		if (www.isDone && string.IsNullOrEmpty(www.error))
		{
			try
			{
				Texture2D imgText = www.texture;
				Rect imgRect = new Rect(0.0f, 0.0f, imgText.width, imgText.height);

				img.sprite = Sprite.Create(imgText, imgRect, new Vector2(0.5f, 0.5f));
				img.gameObject.SetActive(true);
			}
			catch
			{
				Debug.LogError("!!!");
			}
		}
	}
}
